<?php
namespace app\api\controller;

use app\api\controller\Sample;
use app\common\controller\ApiController;
use think\App;
use \app\admin\traits\Curd;
use think\facade\Db;
use app\api\controller\Adv;
use app\api\model\User as ModelUser;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;

class Shop extends ApiController
{
    protected $noNeedLogin = [
        "get_banner_list",
        "get_announcement_list",
        "recommend_service",
        "test",
        "get_protocol_kist",
        "listof_influencers_list",
        "gender_tags",
        "expert_detail",
        "dynamic_List",
        "dynamic_follow",
        "merchant_list",
        
        
    ];
    protected $mustLogin = [];
    protected $counter = 0;

    use \app\admin\traits\Curd;
    public function __construct(App $app)
    {
        parent::__construct($app);
    }
    //轮播图列表
    public function get_banner_list()
    {
        $param = $this->request->param();
        $num = isset($param['num'])?$param['num']:5;
        //type 1首页  2横幅
        if (empty($param['type'])) {
            $this->error('类型不能为空');
        }
        if($param['type'] == 1){
            $list = Db::name("banner")->where("type",$param["type"])->order('id desc')->paginate($num);
        }elseif($param['type'] == 2){
            $list = Db::name("banner")->where("type",$param["type"])->order('id desc')->paginate($num);
        }else{
            $this->error('类型不存在');
        }
        
  
        $this->success('获取成功', $list);
    }
 
    //公告列表
    public function get_announcement_list(){
        $list = Db::name("anx")->order('id desc')->paginate(10);
        $list = $list->toArray();
        $this->success('获取成功', $list);
    }
 
    // //首页达人列表
    // public function listof_influencers_list(){
    //     $list = Db::name("service_goods")->where("is_recommend",1)
    //         ->order('create_time desc')
    //         ->field("id,title,zhu_img,price,duration,is_recommend,salesroom_id")
    //         ->paginate(10)->each(function($item){
    //             $admin = Db::name("system_admin")->where("id",$item["salesroom_id"])->find();
    //             if(!empty($admin)){
    //                 $item["salesroom_name"] = $admin["salesroom_name"];
    //             }else{
    //                 $item["salesroom_name"] = "";
    //             }
    //             return $item;
    //         });
    //     $list = $list->toArray();
    //     $this->success('获取成功', $list);
    // }

   


    //首页达人列表
    public function listof_influencers_list(){
        $param = $this->request->param();
        // 点单榜: 默认按照订单数量从多到少排序，后台可以手动排序  
        // 人气榜: 默认按照点赞数量从多到少排序，后台可以手动调整排序
        // 新人榜: 默认按照后台添加时间倒序，后台可以手动调整排序
        //type 1点单榜  2人气榜  3新人榜
        if (empty($param['type'])) {
            $this->error('类型不能为空');
        }
        $where = [];
        if(!empty($param['service_name']) && isset($param['service_name']))
        {
            $where[] = [
                ['service_name', 'like', '%'.$param['service_name'].'%']
            ];
        }
        if(!empty($param['sex']) && isset($param['sex']))
        {
            $where[] = [
                ['sex', '=',$param['sex']]
            ];
        }
        if(!empty($param['label_id']) && isset($param['label_id']))
        {
            $where[] = [
                ['label_id', 'like', '%'.$param['label_id'].','.'%']
            ];
        }
         

        if($param["type"] == 1){
            $list = Db::name("service_technician")->where($where)->where("status",1)
            ->order("sales_volume desc")
            ->paginate(10)->each(function($item){
                if(empty($item["longitude"]) && empty($item["latitude"])){
                    $item["longitude"] = sysconfig('location','longitude');
                    $item["latitude"] = sysconfig('location','latitude');
                }
                return $item;
            });
        }elseif($param["type"] == 2){
            $list = Db::name("service_technician")->where($where)->where("status",1)
            ->order("like_num desc")
            ->paginate(10)->each(function($item){
                if(empty($item["longitude"]) && empty($item["latitude"])){
                    $item["longitude"] = sysconfig('location','longitude');
                    $item["latitude"] = sysconfig('location','latitude');
                }
                return $item;
            });
        }elseif($param["type"] == 3){
            $list = Db::name("service_technician")->where($where)->where("status",1)
            ->order("create_time desc")
            ->paginate(10)->each(function($item){
                if(empty($item["longitude"]) && empty($item["latitude"])){
                    $item["longitude"] = sysconfig('location','longitude');
                    $item["latitude"] = sysconfig('location','latitude');
                }
                return $item;
            });
        }else{
            $this->error('类型不存在');
        }
        $this->success('获取成功', $list);
    }

    //性别分类标签
    public function gender_tags(){
        $param = $this->request->param();
        //1男  2女
        // if (empty($param['sex'])) {
        //     $this->error('参数传递错误!');
        // }
        if(!empty($param['sex'])){
            $list = Db::name("label")->where("sex",$param["sex"])->select();
        }else{
            $list = [];
        }
      
        $this->success('获取成功', $list);
    }


    //达人详情
    public function expert_detail(){
        $param = $this->request->param();
        if (empty($param['tid'])) {
            $this->error('参数传递错误!');
        }
        $list = Db::name("service_technician")->where("id",$param["tid"])->find();
        if(!empty($list["proficient_in"])){
            $list["proficient_in"] = explode(",",$list["proficient_in"]);
        }
        if(!empty($list["lun_img"])){
            $list["lun_img"] = explode(",",$list["lun_img"]);
        }
        $order_num = Db::name("order")->where("status",2)->count();

        //达人绑定项目
        $service_goods_id = explode(",",$list["service_goods_id"]);
        $service_goods_id = array_filter($service_goods_id);
        $service_goodarr = [];
        foreach($service_goods_id as $ke=>$va){
            $service_goods = Db::name("service_goods")->where("id",$va)->find();
            array_push($service_goodarr,$service_goods);
        }
        //是否已被点赞  is_like
        $my_collection = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$param["tid"])->where("type",1)->find();
        if(!empty($my_collection)){
            $list["is_like"] = true;
        }else{
            $list["is_like"] = false;
        }
        //是否已被收藏 is_follow
        $mycollection = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$param["tid"])->where("type",2)->find();
        if(!empty($mycollection)){
            $list["is_follow"] = true;
        }else{
            $list["is_follow"] = false;
        }

        $list["service_goodarr"] = $service_goodarr;
        $list["order_num"] = $order_num;
        //增加浏览量 
        Db::name("service_technician")->where("id",$param["tid"])->inc("view_volume",1)->update();
        $this->success('获取成功', $list);
    }

     //我的地址列表
     public function myaddress_list(){
        $list = Db::name("address")->where("uid",$this->uid)->order('create_time desc')
            ->paginate(10);
        $this->success('获取成功', $list);
    }

    //地址设置默认
    public function address_set_defalut(){
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        Db::name("address")->where("uid",$this->uid)->update(["is_default"=>0]);
        Db::name("address")->where("uid",$this->uid)->where("id",$param['address_id'])->update(["is_default"=>1]);
        $this->success('设置成功');
    }

    //添加地址
    public function add_address(){
        $param = $this->request->param();
        if(empty($param['username'])){
            $this->error('姓名不能为空');
        }
        if(empty($param['phone'])){
            $this->error('手机号不能为空');
        }
        if(empty($param['address_pca'])){
            $this->error('省市区地址不能为空');
        }
        if(empty($param['address_detailed'])){
            $this->error('详细地址不能为空');
        }
        if(empty($param['longitude'])){
            $this->error('经度不能为空');
        }
        if(empty($param['latitude'])){
            $this->error('纬度不能为空');
        }
        $param["uid"] = $this->uid;
        $param["create_time"] = time();
        Db::name("address")->insert($param);
        $this->success('添加成功');
    }

    //编辑地址显示
    public function address_look(){
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        $list = Db::name("address")->where("id",$param['address_id'])->find();
        $this->success('获取成功', $list);
    }

    //编辑地址
    public function edit_address()
    {
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        if(empty($param['username'])){
            $this->error('姓名不能为空');
        }
        if(empty($param['phone'])){
            $this->error('手机号不能为空');
        }
        if(empty($param['address_pca'])){
            $this->error('省市区地址不能为空');
        }
        if(empty($param['address_detailed'])){
            $this->error('详细地址不能为空');
        }
        if(empty($param['longitude'])){
            $this->error('经度不能为空');
        }
        if(empty($param['latitude'])){
            $this->error('纬度不能为空');
        }
        $address_id = $param["address_id"];
        unset($param["address_id"]);
        Db::name("address")->where("id",$address_id)->update($param);
        $this->success('修改成功');
    }

    //删除地址
    public function del_address(){
        $param = $this->request->param();
        if(empty($param['address_id'])){
            $this->error('未找到指定参数');
        }
        Db::name("address")->where("id",$param['address_id'])->delete();
        $this->success('删除成功');
    }

    //我的默认地址
    public function mu_defa_address(){
        $list = Db::name("address")->where("uid",$this->uid)->where("is_default",1)->find();
        $this->success('获取成功', $list);
    }

     //我的点赞/收藏列表
     public function collection_list(){
        $param = $this->request->param();
        if(empty($param['type'])){
            $this->error('未找到指定类型');
        }
        $list = Db::name("my_collection")->where("uid",$this->uid)->where("type",$param['type'])
        ->paginate(10)->each(function($item){
            $service_technician = Db::name("service_technician")->where("id",$item["tid"])
            ->field("id,uid,service_name,service_img,brief_introduction,settlein_thecity,status_type,longitude,latitude,proficient_in")->find();
            if(empty($service_technician["longitude"]) && empty($service_technician["latitude"])){
                $service_technician["longitude"] = sysconfig('location','longitude');
                $service_technician["latitude"] = sysconfig('location','latitude');
            }
            $item["service_technician"] =$service_technician;
            return $item;
        });
        $list = $list->toArray();
        $this->success('获取成功', $list);
     }

     //添加点赞/收藏
     public function add_collection(){
        $param = $this->request->param();
        if(empty($param['tid'])){
            $this->error('未找到指定产品');
        }
        if(empty($param['type'])){
            $this->error('未找到指定类型');
        }
        
        $flag = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$param['tid'])->where("type",2)->find();
        if(!empty($flag)){
            $this->error('已被收藏不能重复收藏');
        }

        $flag = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$param['tid'])->where("type",1)->find();
        if(!empty($flag)){
            $this->error('已点赞不能重复点赞');
        }
        if($param['type'] == 1){
            Db::name("service_technician")->where("id",$param["tid"])->inc("like_num",1)->update();
        }
        Db::name("my_collection")->insert(["uid"=>$this->uid,"tid"=>$param['tid'],"type"=>$param['type'],"creat_time"=>time()]);
        $this->success('点赞成功');
    }

    //取消点赞/收藏
    public function cancel_collection(){
        $param = $this->request->param();
        if(empty($param['tid'])){
            $this->error('未找到指定产品');
        }
        if(empty($param['type'])){
            $this->error('未找到指定类型');
        }
        if($param['type'] == 1){
            Db::name("service_technician")->where("id",$param["tid"])->dec("like_num",1)->update();
        }
        Db::name("my_collection")->where("tid",$param['tid'])->where("type",$param['type'])->where("uid",$this->uid)->delete();
        $this->success('取消成功');
    }

    //商户列表
    public function merchant_list(){
        $param = $this->request->param();
        $where = [];
        if(!empty($param['merchant_name']) && isset($param['merchant_name']))
        {
            $where[] = [
                ['merchant_name', 'like', '%'.$param['merchant_name'].'%']
            ];
        }
       
         
        $list = Db::name("merchant")->order("id desc")->where($where)
            ->paginate(10)->each(function($item){
                $item["carousel_chart"] = explode(",",$item["carousel_chart"]);
                $item["label"] = explode(",",$item["label"]);
                $item['desc'] = html_entity_decode($item['desc']);
                $item['desc'] = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $item['desc']);
                return $item;
            });
        $this->success('获取成功',$list);
    }

    //上传视频/图片
    public function upload_videoimg()
    {
        $param = $this->request->param();
        if(empty($param['type'])){
            $this->error('未找到指定类型');
        }
        $file = request()->file('file');
        if (empty($file)) {
            $this->error('请选择上传文件');
        }
        if($param['type'] == 1){
            try {
                $filevideo = $_FILES['file'];
                $res = $this->uploadvio($filevideo);
                if($res["code"] == 200){
                    $url = $res["src"];
                }else{
                    $url = "";
                    $this->error('上传失败'); 
                }
                $this->success('上传成功',$url);
            } catch (\think\exception\ValidateException $e) {
                $this->error('上传失败',$e->getMessage());
            }
        }elseif($param['type'] == 2){
            try {
                validate('app\api\validate\Upload')
                    ->scene('img')
                    ->check(['file' => $file]);
                $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
                $url = request()->domain() . '/' . $savename;
                $this->success('上传成功',$url);
            } catch (\think\exception\ValidateException $e) {
                $this->error('上传失败',$e->getMessage());
            }
        }else{
            $this->error('类型错误');
        }
        
    }


    public function uploadvio($file){
        //$file = $_FILES['file'];
        if (!isset($file['tmp_name']) || !$file['tmp_name']) {
            echo json_encode(array('code' => 401, 'msg' => '没有文件上传'));
            return false;
        }
        if ($file["error"] > 0) {
            echo json_encode(array('code' => 402, 'msg' => $file["error"]));
            return false;
        }
      
        $filename = time().rand(0, 1000);
        $ext = pathinfo($_FILES['file']['name'])['extension'];
        $filename = $filename . '.' . $ext;
        $upload_path = "video/";
        
        $domain = ($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
        $save_path =$domain.'/' . $upload_path . $filename;
        if (!is_dir($upload_path)) {
            mkdir(iconv("UTF-8", "UTF-8", $upload_path), 0777, true);
        }
        if (move_uploaded_file($file["tmp_name"], $upload_path . $filename)) {
            return [
                "code"=>200,
                "src"=>$save_path
            ];
        } else {
            return [
                "code"=>404,
                "msg"=>"上传失败"
            ];
        }
    }

    //达人定位打卡
    public function order_clockin(){
        $param = $this->request->param();
        if(empty($param['service_technician_id'])){
            $this->error('达人id不能为空');
        }
        if(empty($param['oid'])){
            $this->error('未找到指定参数');
        }
        //状态（1开始服务，2服务中，3完成服务）
        if(empty($param['type'])){
            $this->error('未找到指定类型');
        }
        if(empty($param['longitude'])){
            $this->error('经度不能为空');
        }
        if(empty($param['latitude'])){
            $this->error('纬度不能为空');
        }
        if(empty($param['address'])){
            $this->error('详细地址不能为空');
        }
        $order = Db::name("order")->where("id",$param["oid"])->where("status","in","2,3,4")->find();
        if(empty($order)){
            $this->error('订单有误,请联系管理员');
        }
        $lfag = Db::name("order_clockin")->where("oid",$param["oid"])->where("type",$param["type"])->where("service_technician_id",$param["service_technician_id"])->find();
        if(empty($lfag)){
            $param["create_time"] = time();
            Db::name("order_clockin")->insert($param);
        }else{
            Db::name("order_clockin")
            ->where("oid",$param["oid"])
            ->where("type",$param["type"])
            ->where("service_technician_id",$param["service_technician_id"])
            ->update($param);
        }
        $this->success('打卡成功');
    }

    //订单打卡记录
    public function check_inrecords(){
        $param = $this->request->param();
        if(empty($param['oid'])){
            $this->error('订单id不能为空');
        }
        $list = Db::name("order_clockin")->where("oid",$param["oid"])->select();
        foreach($list as $k=>$v){
            $v["create_time"] = date("Y-m-d H:i:s",$v["create_time"]);
            $list[$k] = $v;
        }
        $this->success('获取成功',$list);
    }

    //达人发布列表
    public function expert_releaselist(){
        $param = $this->request->param();
        if(empty($param['service_technician_id'])){
            $this->error('未找到指定参数');
        }
        $list = Db::name("dynamic")->where("service_technician_id",$param["service_technician_id"])->paginate(10);
        $list = $list->toArray();
        foreach($list["data"] as $k=>$v){
            $service_technician = Db::name("service_technician")->where("id",$param["service_technician_id"])->find();
            if(!empty($service_technician)){
                $v["like_num"] = $service_technician["like_num"];
            }else{
                $v["like_num"] = 0;
            }
            $v["img"] = explode(",",$v["img"]);
            $v["create_time"] = date("Y-m-d H:i:s",$v["create_time"]);
            $list["data"][$k] = $v;
        }
        $this->success('获取成功',$list);
    }

    //达人发布动态
    public function publish_updates(){
        $param = $this->request->param();
        if(empty($param['type'])){
            $this->error('未找到指定类型');
        }
        if(empty($param['service_technician_id'])){
            $this->error('未找到指定达人');
        }
        if(empty($param['content'])){
            $this->error('未找到指定内容');
        }
        //type 1视频   2图片
        if($param['type'] == 1){
            if(empty($param['video_url'])){
                $this->error('未找到指定参数');
            }
        }elseif($param['type'] == 2){
            if(empty($param['img'])){
                $this->error('未找到指定参数');
            }
        }else{
            $this->error('类型错误');
        }
     
        $param["create_time"] = time();
        $param["uid"] = $this->uid;
        Db::name("dynamic")->insert($param);
        $this->success('发布成功');
    }

    //动态推荐列表
    public function dynamic_List(){
        $list = Db::name("dynamic")->order("create_time desc")
            ->paginate(10)->each(function($item){
                $service_technician = Db::name("service_technician")->where("id",$item["service_technician_id"])
                ->field("id,service_name,service_img,status_type,like_num,view_volume,longitude,latitude")->find();
                //是否已被点赞  is_like
                $my_collection = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$item["service_technician_id"])->where("type",1)->find();
                if(!empty($my_collection)){
                    $item["is_like"] = true;
                }else{
                    $item["is_like"] = false;
                }
                //是否已被收藏 is_follow
                $mycollection = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$item["service_technician_id"])->where("type",2)->find();
                if(!empty($mycollection)){
                    $item["is_follow"] = true;
                }else{
                    $item["is_follow"] = false;
                }
                $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                $item["service_technician"] = $service_technician;
                return $item; 
            });
            $this->success('获取成功',$list);
    }

    //动态关注列表
    public function dynamic_follow(){
        $list = Db::name("dynamic")->alias("dy")
                    ->join("my_collection mc","dy.service_technician_id = mc.tid")
                    ->where("mc.uid",$this->uid)
                    ->where("mc.type",2)
                    ->field("dy.*,mc.uid,mc.tid,mc.type")
                    ->paginate(10)->each(function($item){
                        $service_technician = Db::name("service_technician")->where("id",$item["tid"])
                        ->field("id,service_name,service_img,status_type,like_num,view_volume,longitude,latitude")->find();
                        //是否已被点赞  is_like
                        $my_collection = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$item["tid"])->where("type",1)->find();
                        if(!empty($my_collection)){
                            $item["is_like"] = true;
                        }else{
                            $item["is_like"] = false;
                        }
                        //是否已被收藏 is_follow
                        $mycollection = Db::name("my_collection")->where("uid",$this->uid)->where("tid",$item["tid"])->where("type",2)->find();
                        if(!empty($mycollection)){
                            $item["is_follow"] = true;
                        }else{
                            $item["is_follow"] = false;
                        }
                        $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                        $item["service_technician"] = $service_technician;
                        return $item;
                    });
        $this->success('获取成功',$list);   
    }

    //实名认证
    public function real_name_authentication(){
        $param = $this->request->param();
        if (empty($param['cardNo'])) {
            $this->error('身份证号不能为空');
        }
        if (empty($param['realName'])) {
            $this->error('真实姓名不能为空');
        }
        $host = "https://zidv2.market.alicloudapi.com";
        $path = "/idcheck/Post";
        $method = "POST";
        $appcode = "5d92cf3ddcac457e9eb85d325ab51d58";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $querys = "";
        $bodys = "cardNo=".$param['cardNo']."&realName=".$param['realName'];
        $url = $host . $path;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        list($content, $status) = [curl_exec($curl), curl_getinfo($curl), curl_close($curl)];
        $status = $status; 
        $content = trim(substr($content, $status['header_size']));
        $cont = json_decode($content,true);
        if(!empty($cont["reason"]) && $cont["reason"] == "成功"){
            Db::name("user")->where("id",$this->uid)->update([
                "idcard"=>$param["cardNo"],
                "real_name"=>$param["realName"],
                "is_realname"=>1
            ]);
            $this->success('验证成功',$cont);  
        }else{
            if(empty($cont)){
                $reason = "";
            }else{
                $reason = $cont["reason"];
            }
            $this->error('验证失败',$reason);
        }
    }

    //达人入驻
    public function expert_settlement(){
        $param = $this->request->param();
        if (empty($param['service_name'])) {
            $this->error('昵称不能为空');
        }
        if (empty($param['sex'])) {
            $this->error('性别不能为空');
        }
        if (empty($param['phone'])) {
            $this->error('联系电话不能为空');
        }
        if (empty($param['wechat_number'])) {
            $this->error('微信号码不能为空');
        }
        if (empty($param['date_ofbirth'])) {
            $this->error('出生日期不能为空');
        }
        if (empty($param['settlein_thecity'])) {
            $this->error('入驻城市不能为空');
        }
        if (empty($param['real_name'])) {
            $this->error('真实姓名不能为空');
        }
        if (empty($param['front_ofidcard'])) {
            $this->error('身份证正面不能为空');
        }
        if (empty($param['opposite_ofidcard'])) {
            $this->error('身份证反面不能为空');
        }
        if (empty($param['bankcard_number'])) {
            $this->error('银行卡号不能为空');
        }
        if (empty($param['opening_bank'])) {
            $this->error('开户行不能为空');
        }
        $qwe = Db::name("service_technician")->where("uid",$this->uid)->where("phone",$param["phone"])->where("auditing_status",'in',"0,1")->find();
        if(!empty($qwe)){
            $this->error('此手机号已申请或已通过,请更换');
        }

        $flag = Db::name("service_technician")->where("uid",$this->uid)->where("auditing_status",2)->find();
        if(!empty($flag)){
            $param["create_time"] = time();
            $param["auditing_status"] = 0;
            $param["reason"] = "";
            Db::name("service_technician")->where("uid",$this->uid)->where("auditing_status",2)->update($param);
        }else{
            $param["uid"] = $this->uid;
            $param["create_time"] = time();
            Db::name("service_technician")->insert($param);
        }
        $this->success('提交成功');
       
    }

    //达人入驻状态
    public function expert_settlement_status(){
        $list = Db::name("service_technician")->where("uid",$this->uid)->field("auditing_status,reason")->find();
        if(empty($list)){
            $list = [];
        }
        $this->success('获取成功',$list);
    }

    //获取协议
    public function get_protocol_kist(){
        // $user_agreement = sysconfig("sitepw","user_agreement");
        // $privacy_policy = sysconfig("sitepw","privacy_policy");
        // $ordering_notice = sysconfig("sitepw","ordering_notice");
 
        // $list['privacy_policy'] = html_entity_decode($item['content']);
        // $list['privacy_policy'] = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $item['content']);

        $list['user_agreement'] = $this->rich_text_conversion(sysconfig("sitepw","user_agreement"));
        $list['privacy_policy'] = $this->rich_text_conversion(sysconfig("sitepw","privacy_policy"));
        $list['ordering_notice'] = $this->rich_text_conversion(sysconfig("sitepw","ordering_notice"));
 
        $this->success('获取成功',$list);
    }

    //富文本内容转换
    public function rich_text_conversion($data){
        $data = html_entity_decode($data);
        $data = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $data);
        return $data;
    }

    //扫码绑定上级
    public function scan_code_binding(){
        $param = $this->request->param();
        if (empty($param['fid'])) {
            $this->error('上级id不能为空');
        }
        $user = Db::name("user")->where("id",$param["fid"])->where("is_check",1)->find();
        if(empty($user)){
            $this->error('分销商不存在');
        }
        //查询扫码用户是否是分销商
        $smuser = Db::name("user")->where("id",$this->uid)->find();
        if($smuser["is_check"] != 1){
            Db::name("user")->where("id",$this->uid)->update(["superior_fid"=>$param['fid']]);
        }
        $this->success('绑定成功');
    }

    //提现记录
    public function withdrawal_records(){
        $param = $this->request->param();
        if (empty($param['sid'])) {
            $this->error('达人id不能为空');
        }
        if (empty($param['type'])) {
            $this->error('类型不能为空');
        }
        //1分销商，2陪玩
        if($param["type"] == 1){
            $list = Db::name("withdrawal")->where("uid",$this->uid)->paginate(10);

        }elseif($param["type"] == 2){
            $list = Db::name("withdrawal")->where("uid",$this->uid)->where("service_technician_id",$param["sid"])->paginate(10);
        }else{
            $this->error('类型不存在');
        }
        $this->success('获取成功',$list);

    }

    //分销商佣金明细
    public function get_distributor_commissiondetail(){
        $user = Db::name("user")->where("id",$this->uid)->find();
        if($user["is_check"] == 0){
            $this->error('您不是分销商,不能查看');
        }
        $list = Db::name("commission_record")->where("type",1)->where("superior_fid",$this->uid)->field("id,uid,superior_fid,money,create_time")->paginate(10);
        $list = $list->toArray();
        foreach($list["data"] as $k=>$v){
            $v["create_time"] = date("Y-m-d H:i:s",$v["create_time"]);
            $list["data"][$k]=$v;
        }
        $this->success('获取成功',$list);

    }


    //金融级实人认证-人脸识别
    public function facial_recognition(){
        $param = $this->request->param();
        if (empty($param['certName'])) {
            $this->error('真实姓名不能为空');
        }
        if (empty($param['certNo'])) {
            $this->error('身份证号不能为空');
        }
        if (empty($param['metaInfo'])) {
            $this->error('参数不能为空');
        }
    
        $args["sceneId"] = 1000010413;
        $args["certType"] = "IDENTITY_CARD";
        $args["outerOrderNo"] = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $this->uid;
        $args["productCode"] = "ID_PRO";
        $args["userId"] = $this->uid;
        $args["certName"] = $param["certName"];
        $args["certNo"] = $param["certNo"];
        $args["metaInfo"] = json_encode($param["metaInfo"],true);
        $qaa = Sample::main($args);
        if($qaa["code"] == 200){
            $this->success('验证成功',$qaa);
        }else{
            $this->error('验证失败',$qaa);
        }
    }

    //金融级实人认证-认证详情
    public function DescribeFaceVerify(){
        $param = $this->request->param();
        if (empty($param['certifyId'])) {
            $this->error('认证id不能为空');
        }
        //sha41b6ee62a6b3d1526750cad45539a
        $qaa = DescribeFaceVerify::main(["certifyId"=>$param["certifyId"],"sceneId"=>1000010413]);
        if($qaa["passed"] == "T"){
            Db::name("user")->where("id",$this->uid)->update(["passed"=>$qaa["passed"],"subCode"=>$qaa["subCode"],"is_realname"=>1]);
        }else{
            Db::name("user")->where("id",$this->uid)->update(["passed"=>$qaa["passed"],"subCode"=>$qaa["subCode"]]);
        }
        $this->success('获取成功',$qaa);
    }


    //经纬度转地址
    public function let_transfer_address(){
        $param = $this->request->param();
        if (empty($param['location'])) {
            $this->error('参数不合法');
        }
        if (empty($param['key'])) {
            $this->error('参数不合法');
        }
        $method = 'GET';
        $url = 'https://apis.map.qq.com/ws/geocoder/v1?key='.$param['key'].'&location='.$param["location"];
        $header = [
            'Content-Type:application/json;charset=UTF-8'
        ];
        $res = [];
        $data = $this->urlhttp_curl($url,$method, $res, $header, $timeout = 10);
    
        if(!empty($data) && isset($data) && $data['status'] ==0 && $data['message'] == 'Success' )
        {
            
            $this->success('获取成功',$data);
        }else{
            $this->error('获取失败');
       }

    }







 





































 

    //分割时间段
    function splitTimeIntoHalfHours($startTime, $endTime) {
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);
        $halfHours = array();
     
        while ($startTime <= $endTime) {
            $halfHours[] = date("H:i", $startTime);
            $startTime = strtotime('+10 minutes', $startTime);
        }
        return $halfHours;
    }

    //获取技师预约时间段
    public function gettime_period(){
        $param = $this->request->param();
        // if (empty($param['appointment_date'])) {
        //     $this->error('预约日期不能为空!');
        // }
        if (empty($param['service_technician_id'])) {
            $this->error('技师id不能为空!');
        }
        //根据技师id查询店铺营业时间 salesroom_id
        $service_technician = Db::name("service_technician")->where("id",$param["service_technician_id"])->find();

        $system_admin = Db::name("system_admin")->where("id",$service_technician["salesroom_id"])->find();
        $business_hours = explode("-",$system_admin["business_hours"]);

        //十分钟之后 600秒
        $ten=date("H:i",strtotime($business_hours[1]));
        $halfHours = $this->splitTimeIntoHalfHours($business_hours[0], $ten);

        $this->success('获取成功', $halfHours);
    }
 
    function distance($lat1, $lon1, $lat2, $lon2, $unit) {
        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);
     
        if ($unit == "K") {
            return ($miles * 1.609344);
        } else if ($unit == "N") {
            return ($miles * 0.8684);
        } else {
            return $miles;
        }
    }
     
    // // 使用示例
    // $distance = distance(32.9697, -96.8032, 29.46786, -98.53506, "M"); // 以英里为单位
    // echo $distance . " Miles\n";
     
    // $distance = distance(32.9697, -96.8032, 29.46786, -98.53506, "K"); // 以公里为单位
    // echo $distance . " Kilometers\n";
     
    // $distance = distance(32.9697, -96.8032, 29.46786, -98.53506, "N"); // 以海里为单位
    // echo $distance . " Nautical Miles\n";


    //获取项目下单时间
    public function get_proitime(){

        $aqwe = base64_encode("http://yq.xianmeta.com/upload/20240626/8965ed3f05cfbe1e6812d0609fdc59e9.jpg");
        dump($aqwe);die;

        $param = $this->request->param();
        if (empty($param['service_goods_id'])) {
            $this->error('项目id不能为空!');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('技师id不能为空!');
        }
        if (empty($param['reservation_data'])) {
            $this->error('预约日期不能为空!');
        }
        $list = Db::name("order")
        ->where("status",'in',[2,3])
        ->where("service_goodid",$param["service_goods_id"])
        ->where("service_technician_id",$param["service_technician_id"])
        ->where("appointment_date",$param["reservation_data"])
        ->field("id,appointment_date,appointment_time,time_period,service_duration")
        ->select();
        // 一个小时后的时间
        //$oneHourLater = date('H:i', strtotime('+'.$v["service_duration"].' hour', strtotime($v["appointment_time"])));//strtotime();
        foreach($list as $k=>$v){
            $oneHourLater = [];
            for($i=1;$i<=2;$i++){
                $date = date('H:i', strtotime('+'.$i.' hour', strtotime($v["appointment_time"])));
                array_push($oneHourLater,$date);
            }
            array_unshift($oneHourLater, $v["appointment_time"]);
            $v["oneHourLater"] = $oneHourLater;
            $list[$k]=$v;
        }
        $this->success('获取成功', $list);
    }







 


 
    

 
    

    //服务产品搜索
    public function serive_good_resah(){
        $param = $this->request->param();
        if (empty($param['title'])) {
            $this->error('参数传递错误!');
        }
        $where = [];
        if(!empty($param['title']) && isset($param['title']))
        {
            $where = [
                ['title', 'like', '%'.$param['title'].'%']
            ];
        }
        $list = Db::name("service_goods")->where($where)
        ->order('create_time desc')
        ->field("id,title,zhu_img,server_label")
        ->paginate(10)->each(function($item){
            $service_duration = Db::name("service_duration")->where("service_gid",$item["id"])->order("id asc")->find();
            if(!empty($service_duration)){
                $item["spec_price"] = $service_duration["price"];
            }else{
                $item["spec_price"] = "";
            }
            //好评率
            $zong_num = Db::name("order_evaluate")->where("service_good_id",$item["id"])->count();
            $order_evaluate = Db::name("order_evaluate")->where("service_good_id",$item["id"])->where("star_rating","in","4,5")->count();
            if($zong_num == 0 || $order_evaluate== 0){
                $item["plsz"] =0;
            }else{
                $plsz = bcdiv($order_evaluate,$zong_num,2);
                $plsz = intval($plsz * 100);
                $item["plsz"] =$plsz;
            }
            //已售 
            $sold = Db::name("order")->where("service_gid",$item["id"])->where("status",7)->count();
            $item["sold"] =$sold;
            $item["server_label"] = explode(",",$item["server_label"]);
            return $item;
        });
        $list = $list->toArray();
        $this->success('获取成功', $list);
    } 
 

    //个人数据
    public function personal_data(){
        $cou_num = Db::name("coupon_user")->where("uid",$this->uid)->where("status",1)->count();
        $colle_num = Db::name("my_collection")->where("uid",$this->uid)->count();
        $list = [
            "coupon_num"=>$cou_num,
            "collection_num"=>$colle_num
        ];
        $this->success('获取成功', $list);
    }

    //技师基础资料修改
    public function technician_data_modification(){
        $param = $this->request->param();
        if(empty($param['st_id'])){
            $this->error('未找到指定技师');
        }
        $st_id = $param["st_id"];
        unset($param["st_id"]);
        Db::name("service_technician")->where("id",$st_id)->update($param);
        $this->success('修改成功');
    }

     //上传图片
     public function upload()
     {
         $file = request()->file('file');
         if (empty($file)) {
             $this->error('请选择上传文件');
         }
         try {
             validate('app\api\validate\Upload')
                 ->scene('img')
                 ->check(['file' => $file]);
             $savename = \think\facade\Filesystem::disk('public')->putFile('uploads', $file);
             $url = request()->domain() . '/' . $savename;
             $this->success('上传成功',$url);
         } catch (\think\exception\ValidateException $e) {
             $this->error('上传失败',$e->getMessage());
         }
     }
     
     //技师修改密码
     public function tec_editpwd(){
        $param = $this->request->param();
        if(empty($param['st_id'])){
            $this->error('技师id不能为空');
        }
        if(empty($param['password'])){
            $this->error('新密码不能为空');
        }
        if(empty($param['new_password'])){
            $this->error('密码不能为空');
        }
        if($param['password'] != $param['new_password']){
            $this->error('两次密码不一致');
        }
        Db::name("service_technician")->where("id",$param['st_id'])->update(["password"=>md5($param['password'])]);
        $this->success('修改成功');
     }

     //修改用户信息
     public function modify_user_information(){
        $param = $this->request->param();
        if(empty($param['nickname'])){
            $this->error('昵称不能为空');
        }
        if(empty($param['avatar'])){
            $this->error('头像不能为空');
        }
        if(empty($param['gender'])){
            $this->error('性别不能为空');
        }
        Db::name("user")->where("id",$this->uid)->update($param);
        $this->success('修改成功');
     }

     //配置数据
     public function config_data(){
        $param = $this->request->param();
        if(empty($param['type'])){
            $this->error('类型不能为空');
        }
        if($param["type"] == 1){
            $service_agreement = sysconfig('contact','service_agreement');
            $service_agreement = html_entity_decode($service_agreement);
            $data = str_replace(array("\r", "\n\n", "\s", "\t", "\n"), '<br/>', $service_agreement);
        }elseif($param["type"] == 2){
            $data = sysconfig('site','contact_phone');
        }else{
            $this->error('类型不存在');
        }
        $this->success('获取成功', $data);
     }

 
     //判断是否是服务技师
     public function is_service_technician(){
        $flag = Db::name("service_technician")->where("uid",$this->uid)->find();
        if(empty($flag)){
            $this->error('不是');
        }else{
            $this->success('是',$flag);
        }
        
     }

     //服务技师申请
     public function technician_application(){
        $param = $this->request->param();
        if(empty($param['username'])){
            $this->error('姓名不能为空');
        }
        if(empty($param['img'])){
            $this->error('头像不能为空');
        }
        if(empty($param['age'])){
            $this->error('年龄不能为空');
        }
        if(empty($param['phone'])){
            $this->error('手机号不能为空');
        }
        if(empty($param['sex'])){
            $this->error('性别不能为空');
        }
        $lfag = Db::name("technician_review")->where("status",0)->where("uid",$this->uid)->find();
        if(!empty($lfag)){
            $this->error('已申请,请勿重复申请');
        }
        $flag = Db::name("technician_review")->where("status",2)->where("uid",$this->uid)->find();
        if(!empty($flag)){
            Db::name("technician_review")->where("status",2)->where("uid",$this->uid)->update(["type"=>1]);
        }
        $param["uid"] = $this->uid;
        $param["create_time"] = time();
        Db::name("technician_review")->insert($param);
        $this->success('提交成功');
     }

     //技师审核状态
     public function technician_audit_status(){
        $list = Db::name("technician_review")->where("uid",$this->uid)->where("type",0)->find();
        $this->success('获取成功',$list);
     }

     //商家入驻
     public function merchant_settlement(){
        $param = $this->request->param();
        if(empty($param['call'])){
            $this->error('称呼不能为空');
        }
        if(empty($param['phone'])){
            $this->error('联系电话不能为空');
        }
        if(empty($param['wechat'])){
            $this->error('微信号不能为空');
        }
        if(empty($param['settle_inthecity'])){
            $this->error('入驻城市不能为空');
        }
        $asd = Db::name("merchant_settlement")->where("call",$param["call"])->find();
        if(!empty($asd)){
            $this->error('商户名称已存在,请重新输入');
        }
        $flag = Db::name("merchant_settlement")->where("phone",$param["phone"])->find();
        if(!empty($flag)){
            $this->error('此商户已入驻');
        }
        $param["uid"] = $this->uid;
        $param["create_time"] = time();
        Db::name("merchant_settlement")->insert($param);
        $this->success('申请成功');
     }

     //用户信息
     public function user_information(){
        $list = Db::name("user")->where("id",$this->uid)->find();
        $this->success('获取成功',$list);
     }























     

     

    
 
   
}
